package co.fitstart.admin.web.controller.trade.order;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.search.AllOrderSearch;
import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.CouponService;
import co.fitstart.admin.service.OrderService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.ProductService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.coupon.Coupon;
import co.fitstart.entity.coupon.DiscountType;
import co.fitstart.entity.course.CourseUnit;
import co.fitstart.entity.order.Order;
import co.fitstart.entity.order.OrderType;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.product.Product;
import co.fitstart.entity.site.Site;

/**
 * 
 * @author Ron 
 *
 */
@Controller
@RequestMapping("orders-in")
@MenuSetting("menu-ecommerce")
public class OrderInController {
     
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
   
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private SiteService siteService;

    @Autowired
    private ProductService productService;
    

    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CouponService<Coupon> couponService;
    
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-order-in")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/order-in-list");
        return modelAndView;
    }
    
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    @MenuSetting("submenu-order-in")
    public ModelAndView onSearch(@Secure Login login,
                                 AllOrderSearch allOrderSearch,
                                 @RequestParam(value = "siteId", required = false) Long siteId,
                                 @RequestParam(value = "orderType", required = false) String orderType,
                                 HttpServletRequest request,
                                 Page page) {
        ModelAndView modelAndView = new ModelAndView("ecommerce/order/order-search-list");
        
        if(login.hasSite()) {
            allOrderSearch.setSite(login.getSite());
        } else if(siteId != null) {
            allOrderSearch.setSite(siteService.load(siteId));
        }
        
        if(login.isAreaManager() || login.isAreaServer()) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            allOrderSearch.setSites(siteService.listSite(principal));
        }
        
        if(allOrderSearch.getSites() != null && allOrderSearch.getSites().isEmpty()) {
            modelAndView.addObject("total",0);
        } else {
            OrderType type = OrderType.aliasOf(orderType);
            List<OrderType> orderTypes = new ArrayList<OrderType>();
            
            if(login.isSiteManager() || login.isSiteServer() || login.isAreaManager() || login.isAreaServer()) {
                //不能看线上订单、周边订单
                if(type == OrderType.INDIVIDUAL || type == OrderType.GROUP || type == OrderType.YEAR) {
                    orderTypes.add(type);
                } else {
                    orderTypes.add(OrderType.INDIVIDUAL);
                    orderTypes.add(OrderType.GROUP);
                    orderTypes.add(OrderType.YEAR);
                }
                
                allOrderSearch.setOrderTypes(orderTypes);
            } else if(login.isCustomerServer() || login.isOnlineCoach()) {
                //只能看线上订单
                orderTypes.add(OrderType.ONLINE);

                allOrderSearch.setOrderTypes(orderTypes);
            } else if(login.isCreditProductManager()) {
                //只能看周边订单
                orderTypes.add(OrderType.OTHERS);

                allOrderSearch.setOrderTypes(orderTypes);
            } else {
                if(type != null) {
                    orderTypes.add(type);
                    
                    allOrderSearch.setOrderTypes(orderTypes);
                }
            }
            
            //线上、周边订单无门店
            if(type == OrderType.ONLINE || type == OrderType.OTHERS) {
                allOrderSearch.setSite(null);
            }
            
            // list order by page & status
            List<Order> orders = orderService.search(allOrderSearch, page);
            modelAndView.addObject("orders",orders);
            
            // get total
            int total = orderService.totalOrder(allOrderSearch);
            modelAndView.addObject("total",total);
        }
        
        // add query string
        modelAndView.addObject("refer", "search");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
        
        return modelAndView;
    }
    /**
     * 
     **/
    @RequestMapping(value = "/create-order-in", method = RequestMethod.GET)
    public ModelAndView createGive(@RequestParam(name ="type", required = false) String type) {

        ModelAndView modelAndView = new ModelAndView("ecommerce/order/operations/order-in-create");
        
        modelAndView.addObject("products", productService.listGive());
        modelAndView.addObject("type", type);
        
        return modelAndView;

    }
/**
 *
 * @param mobile
 * @param siteId
 * @param courseHour
 * @return
 * */
    @RequestMapping(value = "/create-order-in", method = RequestMethod.POST)
    public @ResponseBody String onCreateOrderIn(
                         @RequestParam("mobile") String mobile,
                         @RequestParam("name") String name,
                         @RequestParam("siteId") Long siteId,
                         @RequestParam("code") String code,
                         @RequestParam("token") String token,
                         @RequestParam("courseHour") int hours,
                         @RequestParam(name ="type", required = false) String type,
                         @RequestParam(name = "userSourceType", required = false) Long userSourceType,
                         @RequestParam(name ="productType", required = false) String productType,
                         @RequestParam(name = "couponCode", required = false) String couponCode,
                         @RequestParam(name = "courseAttr", required = false) String courseAttr) {
        
        Result result = new Result();
        
        try {
            
            Product product = null;
            Coupon coupon = null;
            
//            String vtoken = DigestUtils.sha256Hex(com.demo2do.core.utils.StringUtils.connect(mobile, code, "fitstart"));
//            logger.info("#checkVerifyCode   token is [{}] and vtoken is [{}]",token,vtoken);
//            boolean validateMObile = StringUtils.equals(vtoken, token);
//            
//            if(!validateMObile) {
//                result.fail().message("手机验证码不正确");
//                return JsonUtils.toJsonString(result);
//            }
            
            if(StringUtils.equalsIgnoreCase(type, "individual")) {
                //product = productService.getProduct(CourseUnit.NORMAL_INDIVIDUAL, hours);
                CourseUnit courseUnit = CourseUnit.aliasOf(productType);
                if(courseUnit==null) {
                    result.fail().message("不存在该类型课程");
                    return JsonUtils.toJsonString(result);
                }
                product = productService.getProduct(courseUnit, hours);
                
            } else if(StringUtils.equalsIgnoreCase(type, "special")) {
                CourseUnit courseUnit = CourseUnit.aliasOf(productType);
                if(courseUnit==null) {
                    result.fail().message("不存在该类型课程");
                    return JsonUtils.toJsonString(result);
                }
                
                if(courseUnit.equals(CourseUnit.SPECIAL_UNION)) {
                	if(StringUtils.isEmpty(courseAttr)) {
                    	result.fail().message("联合课程请选择属性");
                        return JsonUtils.toJsonString(result);
                    }
                	String[] tags = StringUtils.split(courseAttr, ",");
                	if(tags.length <= 1) {
                		result.fail().message("请最少选择两个属性");
                        return JsonUtils.toJsonString(result);
                	}
                	
                }
                
                product = productService.getProduct(courseUnit, hours);
            } else if(StringUtils.equalsIgnoreCase(type, "posture")) {
                CourseUnit courseUnit = CourseUnit.aliasOf(productType);
                if(courseUnit==null) {
                    result.fail().message("不存在该类型课程");
                    return JsonUtils.toJsonString(result);
                }
                product = productService.getProduct(courseUnit, hours);
//                product = productService.getProduct(CourseUnit.NORMAL_POSTURE, hours);
            }
            
            if(StringUtils.isNotBlank(couponCode)) {
                coupon = couponService.loadCoupon(couponCode);
                if(coupon == null) {
                    result.fail().message("无对应的优惠券");
                    return JsonUtils.toJsonString(result);
                }
                
                if(coupon.getDiscountType().equals(DiscountType.GIFT)) {
                    result.fail().message("礼品券不可用于下单");
                    return JsonUtils.toJsonString(result);
                }
                if(!coupon.isAvaliable()) {
                    result.fail().message("优惠券不在使用期限内");
                    return JsonUtils.toJsonString(result);
                }
                
                if(!coupon.getStatus().isUnclaimed()) {
                    result.fail().message("优惠券已使用");
                    return JsonUtils.toJsonString(result);
                }
            }
            
            if (product == null) {
                result.fail().message("不存在该产品");
                return JsonUtils.toJsonString(result);
            } else {
                Site site = siteService.load(siteId);
                orderService.createOrderIn(mobile.trim(), name, product, site, coupon, userSourceType, courseAttr);
                result.success().message("创建课程订单成功，未支付");
                logger.info("create order success here");
            }
            
        } catch (Exception e) {
            result.fail().message(e.getMessage());
            logger.error("error: ", e);
        }
        
        return JsonUtils.toJsonString(result);
    }
}
